package com.itheima.lucene;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;


import java.io.File;
import java.io.IOException;

public class IndexSearchTest {
    public static void main(String[] args) throws IOException, ParseException {

        //创建索引库读取对象
        IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File("F:\\workspace27\\lucene\\index")));


        //创建索引查询类核心对象
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        //封装查询条件: 查询解析器获取方式
        QueryParser queryParser = new QueryParser("content", new IKAnalyzer());
        Query qurery = queryParser.parse("伪娘");
        //执行查询获取查询的结果
        //参数1:查询的条件 2.返回前n条记录
        TopDocs topDocs = indexSearcher.search(qurery, Integer.MAX_VALUE);
        //从结果中获取数据
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;//得分文档数据
        int totalHits = topDocs.totalHits;//整个索引库有多少条记录与之匹配
        System.out.println("总共有:"+totalHits+"条记录与之匹配");
        for (ScoreDoc scoreDoc : scoreDocs) {
            float score = scoreDoc.score; //得分数据 得分越高匹配度越高
            int docId = scoreDoc.doc; //文档的Id值
            Document doc = indexSearcher.doc(docId);//得到在索引库存储的原始数据
            String pid = doc.get("pid");
            String title = doc.get("title");
            String content = doc.get("content");


            System.out.println("文档的得分"+score+"文档内的pid:"+pid+"文档的标题:"+title+"文档的内容:"+ content);

        }

    }


}
